package encrypt

import (
	"fmt"
	"log"

	"gitee.com/smewl13/beehive/pkg/config"
	"gitee.com/smewl13/beehive/pkg/lcrypto"
	"github.com/tjfoc/gmsm/sm4"
)

func NewSM4(file, method string, data []string) *SM4 {
	conf := config.NewConfig(file)
	key := conf.GetString("sm4.key")
	if len(key) != sm4.BlockSize {
		log.Fatalf("sm4加密秘钥长度不正确: %d", len(key))
	}

	return &SM4{
		SM4:    lcrypto.NewSM4(key),
		method: method,
		data:   data,
	}
}

type SM4 struct {
	*lcrypto.SM4
	method string
	data   []string
}

func (sm SM4) handle() {
	var method string
	var fn func([]byte) ([]byte, error)
	switch sm.method {
	case "encode":
		method = "加密"
		fn = sm.Encrypt
	case "decode":
		method = "解密"
		fn = sm.Decrypt
	}

	fmt.Printf("数据%s开始...\n", method)
	for i, item := range sm.data {
		buf, err := fn([]byte(item))
		if err != nil {
			log.Fatalf("SM4%s失败, data: %s, err: %v\n", method, item, err)
		}

		fmt.Printf("============ %d ============\n", i)
		fmt.Printf("input: %s\n", item)
		fmt.Printf("output: %s\n", string(buf))
		fmt.Println()
	}
}
